import React, { forwardRef, useEffect, useImperativeHandle } from 'react';
import { useState } from 'react';
import {
  Drawer,
  Button,
  Grid,
  Space,
  Input,
  Link,
  Popover,
  Tree,
  Popconfirm,
  Message,
} from '@arco-design/web-react';
import styles from './style/index.module.less';
import {
  IconAlignLeft,
  IconDelete,
  IconPlus,
} from '@arco-design/web-react/icon';
import {
  addKnowledgeApi,
  addSectionApi,
  deleteKnowledgeApi,
  deleteSectionApi,
  editKnowledgeApi,
  editSectionApi,
  getKnowledgeApi,
  getSectionAllApi,
  getSectionApi,
} from '@/request/api';
import AboutLesson from '@/pages/system/course/aboutLesson';
const Row = Grid.Row;
const Col = Grid.Col;
const LessonTitle = ({ name }) => {
  return (
    <Row justify={'space-between'} align={'center'}>
      <Space>
        <div className={styles['lesson-title']}>课程</div>
        <div>{name}</div>
      </Space>
      {/*<Space>*/}
      {/*  <Button type={'primary'}>协同</Button>*/}
      {/*  <Button type={'primary'}>保存</Button>*/}
      {/*  <Button type={'primary'}>取消</Button>*/}
      {/*</Space>*/}
    </Row>
  );
};

const LessonDrawer = forwardRef((props, ref) => {
  const [info, setInfo] = useState({ schCourseId: -1, schCourseName: '' });
  const [visible, setVisible] = useState(false);
  const [newSectionName, setNewSectionName] = useState('');
  const [visibleInput, setVisibleInput] = useState(false);

  const [treeData, setTreeData] = useState([]);
  const [selectNode, setSelectNode] = useState({});

  useEffect(() => {
    fetchTreeData();
  }, [JSON.stringify(info)]);

  const addSection = () => {
    addSectionApi({ schCourseId: info.schCourseId, name: newSectionName })
      .then((res) => {
        const { msg } = res;
        Message.success(msg);
        fetchTreeData();
      })
      .catch((e) => {
        console.log(e);
      });
  };

  const deleteSection = (id) => {
    deleteSectionApi({ id: id })
      .then((res) => {
        const { msg } = res;
        Message.success(msg);
        fetchTreeData();
      })
      .catch((e) => {
        console.log(e);
      });
  };

  const editSection = (info) => {
    editSectionApi(info)
      .then((res) => {
        const { msg } = res;
        Message.success(msg);
        fetchTreeData();
      })
      .catch((e) => {
        console.log(e);
      });
  };

  const fetchTreeData = () => {
    getSectionApi({
      schCourseId: info.schCourseId,
      pageNum: 1,
      pageSize: 100,
    })
      .then((res) => {
        const { data } = res;
        setTreeData(data.list);
      })
      .catch((e) => {
        console.log(e);
      });
  };

  const addKnowledge = (info) => {
    addKnowledgeApi(info)
      .then((res) => {
        const { msg } = res;
        Message.success(msg);
        fetchTreeData();
      })
      .catch((e) => {
        console.log(e);
      });
  };

  const editKnowledge = (info) => {
    editKnowledgeApi(info)
      .then((res) => {
        const { msg } = res;
        Message.success(msg);
        fetchTreeData();
      })
      .catch((e) => {
        console.log(e);
      });
  };

  const deleteKnowledge = (id) => {
    deleteKnowledgeApi({ id: id })
      .then((res) => {
        const { msg } = res;
        Message.success(msg);
        fetchTreeData();
      })
      .catch((e) => {
        console.log(e);
      });
  };

  const loadMore = (treeNode) => {
    console.log(treeNode, 'treeNode');
    return getKnowledgeApi({
      schCourseId: info.schCourseId,
      schCourseChapterId: treeNode.props.dataRef.id,
      pageNum: 1,
      pageSize: 100,
      type: treeNode.props.dataRef.type === 0 ? 1 : 0,
    })
      .then((res) => {
        const { data } = res;
        treeNode.props.dataRef.children = data.list;
        setTreeData([...treeData]);
      })
      .catch((e) => {
        console.log(e);
      });
  };

  useImperativeHandle(ref, () => ({
    setVisible: (newVal) => {
      setVisible(newVal);
    },
    setInfo: (newVal) => {
      setInfo(newVal);
    },
  }));

  return (
    <Drawer
      width={'80%'}
      title={null}
      footer={null}
      visible={visible}
      closable={false}
      onOk={() => {
        setVisible(false);
      }}
      onCancel={() => {
        setVisible(false);
      }}
    >
      <LessonTitle name={info.schCourseName}></LessonTitle>
      <Row>
        <Col span={6}>
          <Space>
            <h3>课程章节</h3>
            <Popover
              position={'right'}
              title="课程章节"
              popupVisible={visibleInput} // button 触发 mouseenter的时候会调用该方法。更多的用法可以查看Trigger组件。
              content={
                <span>
                  <Input
                    allowClear
                    placeholder={`章节名称`}
                    onChange={(value) => {
                      setNewSectionName(value);
                    }}
                  />
                  <Space align={'end'} style={{ marginTop: 10 }}>
                    <Link
                      onClick={() => {
                        setVisibleInput(false);
                      }}
                    >
                      取消
                    </Link>
                    <Link onClick={() => addSection()}>增加</Link>
                  </Space>
                </span>
              }
            >
              <Button
                size={'small'}
                icon={<IconPlus />}
                style={{
                  fontSize: 12,
                  color: '#3370ff',
                  backgroundColor: '#ffffff',
                }}
                onClick={() => {
                  setVisibleInput(true);
                }}
              ></Button>
            </Popover>
          </Space>
          <Tree
            fieldNames={{
              key: 'createTime',
              title: 'name',
              children: 'children',
            }}
            loadMore={loadMore}
            showLine={true}
            treeData={treeData}
            onSelect={(keys, extra) => {
              setSelectNode(extra.node.props.dataRef);
            }}
            renderExtra={(node) => {
              return (
                <div>
                  {node.dataRef.type !== 1 ? (
                    <Popover
                      title={null}
                      popupVisible={node.dataRef.visiblePlus} // button 触发 mouseenter的时候会调用该方法。更多的用法可以查看Trigger组件。
                      content={
                        <span>
                          <Input
                            allowClear
                            onChange={(value) => {
                              node.dataRef.inputValue = value;
                            }}
                          />
                          <Space align={'end'} style={{ marginTop: 10 }}>
                            <Link
                              onClick={() => {
                                node.dataRef.visiblePlus = false;
                                setTreeData([...treeData]);
                              }}
                            >
                              取消
                            </Link>
                            <Link
                              onClick={() => {
                                addKnowledge({
                                  schCourseChapterId: node.dataRef.id,
                                  name: node.dataRef.inputValue,
                                  type: node.dataRef.type === 0 ? 1 : 0,
                                });
                              }}
                            >
                              增加
                            </Link>
                          </Space>
                        </span>
                      }
                    >
                      <Button
                        size={'mini'}
                        style={{
                          position: 'absolute',
                          right: 50,
                          fontSize: 12,
                          top: 5,
                          color: '#3370ff',
                          backgroundColor: '#ffffff',
                        }}
                        icon={<IconPlus />}
                        onClick={() => {
                          node.dataRef.visiblePlus = true;
                          setTreeData([...treeData]);
                        }}
                      ></Button>
                    </Popover>
                  ) : null}

                  <Popover
                    title="修改"
                    popupVisible={node.dataRef.visible} // button 触发 mouseenter的时候会调用该方法。更多的用法可以查看Trigger组件。
                    content={
                      <span>
                        <Input
                          allowClear
                          placeholder={`${node.dataRef.name}`}
                          onChange={(value) => {
                            node.dataRef.inputValue = value;
                          }}
                        />
                        <Space align={'end'} style={{ marginTop: 10 }}>
                          <Link
                            onClick={() => {
                              node.dataRef.visible = false;
                              setTreeData([...treeData]);
                            }}
                          >
                            取消
                          </Link>
                          <Link
                            onClick={() => {
                              console.log(node, 'edit');
                              if (node.dataRef.type > -1) {
                                console.log(233333);
                                editKnowledge({
                                  id: node.dataRef.id,
                                  name: node.dataRef.inputValue,
                                });
                              } else {
                                console.log(244444);
                                editSection({
                                  id: node.dataRef.id,
                                  name: node.dataRef.inputValue,
                                });
                              }
                            }}
                          >
                            修改
                          </Link>
                        </Space>
                      </span>
                    }
                  >
                    <Button
                      size={'mini'}
                      style={{
                        position: 'absolute',
                        right: 30,
                        fontSize: 12,
                        top: 5,
                        color: '#3370ff',
                        backgroundColor: '#ffffff',
                      }}
                      icon={<IconAlignLeft />}
                      onClick={() => {
                        node.dataRef.visible = true;
                        setTreeData([...treeData]);
                      }}
                    ></Button>
                  </Popover>
                  <Popconfirm
                    focusLock
                    icon={null}
                    title="确定删除吗?"
                    onOk={() => {
                      if (node.dataRef.type > -1) {
                        deleteKnowledge(node.dataRef.id);
                      } else {
                        deleteSection(node.dataRef.id);
                      }
                    }}
                  >
                    <Button
                      style={{
                        position: 'absolute',
                        right: 6,
                        fontSize: 12,
                        top: 5,
                        color: '#3370ff',
                        backgroundColor: '#ffffff',
                      }}
                      size={'mini'}
                      icon={<IconDelete />}
                      onClick={() => {
                        setTreeData([...treeData]);
                      }}
                    ></Button>
                  </Popconfirm>
                </div>
              );
            }}
          ></Tree>
        </Col>
        <Col span={18}>
          {/*<div>{selectNode.name}</div>*/}
          <AboutLesson node={selectNode} info={info}></AboutLesson>
        </Col>
      </Row>
    </Drawer>
  );
});

export default LessonDrawer;
